"use client"

import * as React from "react"
import { Search, MoreHorizontal, Plus, RefreshCwIcon as Refresh } from "lucide-react"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { ScrollArea } from "@/components/ui/scroll-area"
import { FileTree } from "./file-tree"
import type { FileNode } from "@/types/file-tree"

interface VSCodeSidebarProps {
  fileData: FileNode[]
  onFileSelect?: (file: FileNode) => void
}

export function VSCodeSidebar({ fileData, onFileSelect }: VSCodeSidebarProps) {
  const [searchTerm, setSearchTerm] = React.useState("")

  const filteredData = React.useMemo(() => {
    if (!searchTerm) return fileData

    const filterNodes = (nodes: FileNode[]): FileNode[] => {
      return nodes.reduce((acc: FileNode[], node) => {
        if (node.name.toLowerCase().includes(searchTerm.toLowerCase())) {
          acc.push(node)
        } else if (node.children) {
          const filteredChildren = filterNodes(node.children)
          if (filteredChildren.length > 0) {
            acc.push({ ...node, children: filteredChildren })
          }
        }
        return acc
      }, [])
    }

    return filterNodes(fileData)
  }, [fileData, searchTerm])

  return (
    <div className="w-64 h-full bg-background border-r border-border flex flex-col">
      {/* Header */}
      <div className="flex items-center justify-between p-2 border-b border-border">
        <span className="text-sm font-medium text-foreground/80 uppercase tracking-wide">Explorer</span>
        <div className="flex items-center gap-1">
          <Button variant="ghost" size="icon" className="h-6 w-6">
            <Plus className="h-3 w-3" />
          </Button>
          <Button variant="ghost" size="icon" className="h-6 w-6">
            <Refresh className="h-3 w-3" />
          </Button>
          <Button variant="ghost" size="icon" className="h-6 w-6">
            <MoreHorizontal className="h-3 w-3" />
          </Button>
        </div>
      </div>

      {/* Search */}
      <div className="p-2 border-b border-border">
        <div className="relative">
          <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-3 w-3 text-muted-foreground" />
          <Input
            placeholder="Search files..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-7 h-7 text-xs bg-muted/50 border-0 focus-visible:ring-1"
          />
        </div>
      </div>

      {/* File Tree */}
      <ScrollArea className="flex-1">
        <div className="p-1">
          <FileTree data={filteredData} onFileSelect={onFileSelect} />
        </div>
      </ScrollArea>
    </div>
  )
}
